import React, { useState, useEffect, useRef } from 'react'
import './Danmaku.css'

interface TimedDanmaku {
  text: string
  color: string
  triggerTime: number
  duration: number
}

interface DanmakuItem {
  id: string
  text: string
  color: string
  top: number
  duration: number
  fontSize?: number
  // 运行时位置与速度（像素/秒）
  xPx?: number
  baseSpeedPx?: number
}

interface DanmakuProps {
  currentTime: number
  isPlaying: boolean
  // 注册一个外部添加弹幕的方法
  onRegisterAdd?: (api: (payload: { text: string; color?: string; fontSize?: number; speed?: number }) => void) => void
  // 全局速度倍速（1-5），影响在场与后续弹幕
  speed?: number
  // 弹幕启用/禁用
  enabled?: boolean
}

// 模拟弹幕数据
const timedDanmakuData: TimedDanmaku[] = [
  { text: '视频开始播放！', color: '#00d4ff', triggerTime: 0, duration: 3 },
  { text: '原来这就是数字人呀！', color: '#ff6b6b', triggerTime: 1, duration: 3 },
  { text: '大海也是挺厉害的', color: '#00d4ff', triggerTime: 2, duration: 3 },
  { text: 'XXX我替你看到大海了', color: '#00ff88', triggerTime: 2, duration: 3 },
  { text: '海洋里面这么可怕呀，我还以为很美丽呢', color: '#ffaa00', triggerTime: 5, duration: 3 },
  { text: '啊啊啊啊', color: '#00d4ff', triggerTime: 7, duration: 3 },
  { text: '牛逼', color: '#ff6b6b', triggerTime: 9, duration: 3 },
  { text: '好美丽！', color: '#00d4ff', triggerTime: 10, duration: 3 },
  { text: '欢迎来到3D世界', color: '#ff6b6b', triggerTime: 5, duration: 4 },
  { text: '数字人技术真棒', color: '#00ff88', triggerTime: 10, duration: 4 },
  { text: '继续观看精彩内容', color: '#ffaa00', triggerTime: 15, duration: 4 },
  { text: '感谢观看！', color: '#ff6b6b', triggerTime: 20, duration: 3 }
]

const Danmaku: React.FC<DanmakuProps> = ({ currentTime, isPlaying, onRegisterAdd, speed = 3, enabled = true }) => {
  const [danmakuList, setDanmakuList] = useState<DanmakuItem[]>([])
  const triggeredRef = useRef<Set<number>>(new Set())
  const idCounterRef = useRef(0)
  const rafRef = useRef<number | null>(null)
  const lastTsRef = useRef<number | null>(null)
  const containerRef = useRef<HTMLDivElement>(null)

  // 将起点设置在视频区域右侧，距离等于弹幕自身宽度，实现与左侧离场对称
  const placeStartOutsideRight = (id: string) => {
    const containerWidth = containerRef.current?.clientWidth ?? 0
    const el = document.getElementById(id)
    const w = el?.offsetWidth ?? 0
    if (!w) return
    const startX = containerWidth + w
    setDanmakuList(prev => prev.map(d => d.id === id ? { ...d, xPx: startX } : d))
  }

  // 生成随机垂直位置
  const getRandomTop = () => {
    return Math.random() * 60 + 20 // 20% 到 80% 之间
  }

  // 检查并触发弹幕
  useEffect(() => {
    if (!isPlaying || !enabled) return

    timedDanmakuData.forEach((danmaku, index) => {
      // 检查是否到了触发时间且未触发过
      if (
        currentTime >= danmaku.triggerTime && 
        !triggeredRef.current.has(index)
      ) {
        triggeredRef.current.add(index)
        
        const containerWidth = containerRef.current?.clientWidth ?? 0
        const newDanmaku: DanmakuItem = {
          id: `danmaku-${idCounterRef.current++}`,
          text: danmaku.text,
          color: danmaku.color,
          top: getRandomTop(),
          duration: danmaku.duration,
          // 先临时放在容器右缘，下一帧测量宽度后放到“完全在右侧外”的对称起点
          xPx: containerWidth,
          baseSpeedPx: 90, // 基础速度 px/s（默认更慢）
        }

        setDanmakuList(prev => [...prev, newDanmaku])
        // 下一帧基于元素宽度把起点放到右侧完全不可见处
        requestAnimationFrame(() => placeStartOutsideRight(newDanmaku.id))

        // 设置定时器移除弹幕
        // 不再使用超时移除，由动画循环按位置清理
      }
    })
  }, [currentTime, isPlaying, enabled])

  // 视频重置时清空已触发的记录
  useEffect(() => {
    if (currentTime < 1) {
      triggeredRef.current.clear()
      setDanmakuList([])
    }
  }, [currentTime])

  // 向外暴露添加弹幕的方法
  useEffect(() => {
    if (!onRegisterAdd) return
    const add = (payload: { text: string; color?: string; fontSize?: number; speed?: number }) => {
      if (!enabled) return
      const { text, color = '#ffffff', fontSize = 16, speed: itemSpeed = 3 } = payload
      const clamped = Math.max(1, Math.min(5, itemSpeed))
      const baseSpeedPx = 90 * clamped // px/s（默认更慢）
      const containerWidth = containerRef.current?.clientWidth ?? 0
      const duration = 6 // 保留字段，不用于驱动
      const item: DanmakuItem = {
        id: `ext-${idCounterRef.current++}`,
        text,
        color,
        top: getRandomTop(),
        duration,
        fontSize,
        // 与定时弹幕一致：临时放右缘，下一帧移到“右侧完全不可见”处
        xPx: containerWidth,
        baseSpeedPx,
      }
      setDanmakuList(prev => [...prev, item])
      requestAnimationFrame(() => placeStartOutsideRight(item.id))
    }
    onRegisterAdd(add)
  }, [onRegisterAdd, enabled])

  // 动画循环：基于全局speed与各自baseSpeed推进x位置
  useEffect(() => {
    if (!isPlaying || !enabled) {
      // 暂停时停止帧循环
      if (rafRef.current) cancelAnimationFrame(rafRef.current)
      rafRef.current = null
      lastTsRef.current = null
      return
    }

    const tick = (ts: number) => {
      if (lastTsRef.current == null) lastTsRef.current = ts
      const dt = (ts - lastTsRef.current) / 1000
      lastTsRef.current = ts

      const global = Math.max(0.5, Math.min(5, speed))
      setDanmakuList(prev => {
        const next: DanmakuItem[] = []
        for (const it of prev) {
          const v = (it.baseSpeedPx || 90) * global
          const x = (it.xPx ?? 0) - v * dt
          // 使用元素真实宽度作为移除阈值
          const elem = document.getElementById(it.id)
          const removeLeft = -(elem?.offsetWidth ?? 200)
          if (x > removeLeft) {
            next.push({ ...it, xPx: x })
          }
        }
        return next
      })

      rafRef.current = requestAnimationFrame(tick)
    }
    rafRef.current = requestAnimationFrame(tick)

    return () => {
      if (rafRef.current) cancelAnimationFrame(rafRef.current)
      rafRef.current = null
      lastTsRef.current = null
    }
  }, [isPlaying, speed, enabled])

  // 禁用时清空屏幕
  useEffect(() => {
    if (!enabled) {
      setDanmakuList([])
      triggeredRef.current.clear()
    }
  }, [enabled])

  return (
    <div className="danmaku-container" ref={containerRef}>
      {danmakuList.map((danmaku) => (
        <div
          key={danmaku.id}
          id={danmaku.id}
          className="danmaku-item"
          style={{
            color: danmaku.color,
            top: `${danmaku.top}%`,
            fontSize: danmaku.fontSize ? `${danmaku.fontSize}px` : undefined,
            transform: `translateX(${danmaku.xPx ?? 0}px)`,
          }}
        >
          {danmaku.text}
        </div>
      ))}
    </div>
  )
}

export default Danmaku
